using System.Threading;
using System.Threading.Tasks;
using MediatR;
using admin.application.Notifications;
using Microsoft.Extensions.Logging;

namespace admin.application.Services
{
    public class RoleCreatedEventHandler : INotificationHandler<RoleCreatedNotification>
    {
        private readonly IAppRoleServices _roleServices;
        private readonly IAppPermissionService _permissionService;
        private readonly ILogger<RoleCreatedEventHandler> _logger;
        public RoleCreatedEventHandler(IAppRoleServices roleServices, IAppPermissionService permissionService, ILogger<RoleCreatedEventHandler> logger)
        {
            _roleServices = roleServices;
            _permissionService = permissionService;
            _logger = logger;
        }
        public async Task Handle(RoleCreatedNotification notification, CancellationToken cancellationToken)
        {
            var roleId = notification.Event.RoleId;
            _logger.LogInformation("处理角色创建事件，角色ID: {RoleId}", roleId);
            var defaultPermission = await _permissionService.GetByCodeAsync("Default.Permission");
            if (defaultPermission != null)
            {
                await _roleServices.AssignPermissionAsync(roleId, defaultPermission.Id);
                _logger.LogInformation("已为角色 {RoleId} 分配默认权限 {PermissionId}", roleId, defaultPermission.Id);
            }
            else
            {
                _logger.LogWarning("未找到默认权限，角色ID: {RoleId}", roleId);
            }
        }
    }
} 